package com.yc.chatroom.client;

import com.yc.chatroom.common.dto.BaseDto;
import com.yc.chatroom.common.dto.LoginResponse;
import com.yc.chatroom.common.dto.MsgDto;
import com.yc.chatroom.common.dto.ShowMsgDto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandle extends ChannelInboundHandlerAdapter {
	
	private ClientManager client;
	public ClientHandle(ClientManager clientManager) {
		this.client = clientManager;
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		String body = "你好，我是客户端: " + Thread.currentThread().getName();
//		byte[] bytes = body.getBytes("UTF-8");
//		
//		ByteBuf buf = Unpooled.buffer(bytes.length);
//		buf.writeBytes(bytes);
		
		System.out.println("----------channelActive--------");
//		MsgDto md = new MsgDto(1, "张三", "abcdafsas消息", System.currentTimeMillis());
//		
//		ctx.writeAndFlush(md);
		
	}
	
	/**
	 * 服务器应答消息后
	 * 服务器随时发消息都能收到吗？
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//		ByteBuf buf = (ByteBuf) msg;
//		byte[] bytes = new byte[buf.readableBytes()];
//		
//		buf.writeBytes(bytes);
//		String body = new String(bytes, "UTF-8");
//		System.out.println(body);
		
		System.out.println("------channelRead0-----");
		if (msg instanceof ShowMsgDto) {//普通消息
			System.out.println("------ShowMsgDto-----" + ((ShowMsgDto) msg).getMessage());
			client.MSG_QUEUE.put((ShowMsgDto) msg);
		} else if (msg instanceof LoginResponse) {//登录返回消息
			System.out.println("------LoginResponse-----" + ((LoginResponse) msg).getMsg());
			client.loginResponse = (LoginResponse) msg;
		}
		
	}


	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}



	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();//如果该通道出现异常，到这里把该通道关闭（ChannelHandlerContext中封装着通道，所以说ctx或channel意义差不多）
	}



//	@Override
//	protected void channelRead0(ChannelHandlerContext ctx, BaseDto msg) throws Exception {
//		ShowMsgDto msgContent = (ShowMsgDto) msg;
//		String message = msgContent.getMessage();
//		System.out.println("------channelRead0-----" + message);
//		// 1. 接收并封装消息
//		MainClient.MSG_QUEUE.put(msgContent);
//		
//	}

	
}
